#import "MRChartView.h"

@interface MRChartContentView : UIView
@end

/*===================================================================
 说明:
    图表参考线
 ==================================================================*/
#pragma mark - 图表参考线
@implementation MRChartLine

- (id)initWithChart:(MRChart *)chart
{
	if (self = [super init])
	{
		_chart = chart;
		
		_lineWidth = SINGLE_LINE_WIDTH;
		_lineDash  = chart.lineDash;
		_lineColor = chart.lineColor;
        _textColor = chart.textColor;
		_textFont  = chart.textFont;
		_textAlign = CGPointMake(MRTextAlignmentCenter, MRTextAlignmentTop);
	}
	
	return self;
}

@end

/*===================================================================
 说明:
    图表
 ==================================================================*/
#pragma mark - 图表配置
@implementation MRChart

- (id)initWithChartView:(MRChartView *)chartView
{
    if (self = [super init])
    {
		_chartView = chartView;
		
        _lines  = [NSMutableArray array];
		_points = [NSMutableArray array];
        
		_lineColor = [UIColor clearColor];
		_fillColor = [UIColor clearColor];
		_textFont  = [UIFont systemFontOfSize:[UIScreen mainScreen].bounds.size.width * 8 / 320];
        _textAlign = CGPointMake(MRTextAlignmentLeft, MRTextAlignmentTop);
        
        _continuous = YES;
        _maxValue   = 1.0;
        _lineWidth  = 2.0;
    }
	
    return self;
}

/*===================================================================
 说明:
    添加参考线
 ==================================================================*/
- (MRChartLine *)addLineWithText:(NSString *)text value:(CGFloat)value
{
    MRChartLine *line = [[MRChartLine alloc] initWithChart:self];
	line.text  = text;
    line.value = value;
	
	[_lines addObject:line];
    return line;
}

/*===================================================================
 说明:
	添加数据点
 ==================================================================*/
- (void)addPointWithDictionary:(NSDictionary *)dictionary
{
	for (NSNumber *d in dictionary.allKeys)
	{
		NSDictionary *dict = @{d:dictionary[d]};
		
		//按索引顺序插入到对应位置，如果已存在则替换
		NSInteger i = _points.count-1;
		for (; i>=0; i--)
		{
			CGFloat last = [[_points[i] allKeys].firstObject floatValue];
			
			if (d.floatValue > last)
			{
				[_points insertObject:dict atIndex:i+1];
				break;
			}
			else if (d.floatValue == last)	//替换对象
			{
				[_points replaceObjectAtIndex:i withObject:dict];
				break;
			}
		}
		
		if (i == -1) [_points insertObject:dict atIndex:0];
	}
}

- (void)addPointWithArray:(NSArray *)points
{
	for (NSDictionary *dict in points)
		[self addPointWithDictionary:dict];
}

@end

#pragma mark - 图表视图
/*===================================================================
 说明:
    图表视图
 ==================================================================*/
@implementation MRChartView
{
    MRChartContentView  *_contentView;
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
		self.alwaysBounceHorizontal = YES;
		self.showsHorizontalScrollIndicator = NO;
		self.showsVerticalScrollIndicator = NO;
		self.backgroundColor = [UIColor clearColor];
		
        [self awakeFromNib];
    }
	
    return self;
}

//初始化
- (void)awakeFromNib
{
	[super awakeFromNib];
	self.scrollsToTop = NO;
	//self.bounces = NO;
	//self.alwaysBounceHorizontal = YES;
	
    _charts = [NSMutableArray array];
	_allowZoom = YES;
	
	_minPointWidth = DPISCALE(2);
	_maxPointWidth = DPISCALE(25);
	
    _gridDash  = @[@2, @2];
	_gridWidth = SINGLE_LINE_WIDTH;
    _gridColor = rgba(127, 127, 127, .2);
	_borderColor = rgba(127, 127, 127, .8);
    
    if (_gridSize.height == 0)
        _gridSize = CGSizeMake(0, 6);
	
	if (UIEdgeInsetsEqualToEdgeInsets(_border, UIEdgeInsetsZero))
		_border = UIEdgeInsetsMake(SINGLE_LINE_WIDTH, SINGLE_LINE_WIDTH, SINGLE_LINE_WIDTH, SINGLE_LINE_WIDTH);
	
	_footer = [[MRChart alloc] initWithChartView:self];
	_footer.lineWidth = SINGLE_LINE_WIDTH;
	_footer.lineDash  = @[@2, @2];
	_footer.lineColor = _gridColor;
	_footer.textColor = [UIColor whiteColor];
	_footer.textFont  = [UIFont systemFontOfSize:[UIScreen mainScreen].bounds.size.width * 9 / 320];
    _footer.textAlign = CGPointMake(MRTextAlignmentCenter, MRTextAlignmentVCenter);
	
	if (_footerHeight == 0)
		_footerHeight = LOCPIXEL(DPISCALE(18));
	
	_footerAlign = CGPointMake(MRTextAlignmentRight, MRTextAlignmentVCenter);
    _footerColor = rgb(127, 127, 127);
	
	_contentView = [MRChartContentView new];
	_contentView.backgroundColor = [UIColor clearColor];
	[self insertSubview:_contentView atIndex:0];
	
	_gestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
	[self addGestureRecognizer:_gestureRecognizer];
}

/*===================================================================
 说明:
    缩放手势
 ==================================================================*/
- (void)pinchGesture:(UIPinchGestureRecognizer *)gesture
{
	static CGFloat width;
	static CGFloat scale;
	static CGPoint offset;
	
	if (!_allowZoom) return;
	
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
		CGPoint p1 = [gesture locationOfTouch:0 inView:self];
		CGPoint p2 = [gesture locationOfTouch:1 inView:self];
		
		scale  = (p1.x + p2.x) / 2 / self.bounds.size.width;
		offset = self.contentOffset;
		width  = self.pointWidth;
    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
		[self setPointWidth:width * gesture.scale];
		
		/*CGFloat x = offset.x + (_width - width) * scale;
		if (_width < self.bounds.size.width) x = 0;
		
		self.contentOffset = CGPointMake(x, offset.y);*/
    }
}

/*===================================================================
 说明:
	设置点宽度及数量
 ==================================================================*/
- (void)setPointWidth:(CGFloat)pointWidth
{
	if (_minPointWidth && pointWidth < _minPointWidth) pointWidth = _minPointWidth;
	if (_maxPointWidth && pointWidth > _maxPointWidth) pointWidth = _maxPointWidth;
	
	_pointWidth = pointWidth;
	if (_pointCount) self.contentSize = CGSizeMake(_pointWidth * _pointCount, 0);
}

- (void)setPointCount:(CGFloat)pointCount
{
	if (pointCount > _pointCount)
	{
		[self setPointCount:pointCount animated:YES];
	}
}

- (void)setPointCount:(CGFloat)pointCount animated:(BOOL)animated
{
	_pointCount = pointCount;
	
	if (_pointWidth)
	{
		self.contentSize = CGSizeMake(_pointWidth * _pointCount, 0);
		
		CGPoint point = self.contentOffset;
		point.x = self.contentSize.width - self.bounds.size.width;
		[self setContentOffset:point animated:animated];
	}
}

/*===================================================================
 说明:
	滚动时重绘曲线
 ==================================================================*/
- (void)setContentOffset:(CGPoint)contentOffset
{
	[super setContentOffset:contentOffset];
	_contentView.frame = self.bounds;
	[_contentView setNeedsDisplay];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
	return _contentView;
}

- (void)setNeedsDisplay
{
    [self layoutIfNeeded];
    [super setNeedsDisplay];
    [_contentView setNeedsDisplay];
}

#pragma mark - 绘制图表
/*===================================================================
 说明:
	设置线样式
 ==================================================================*/
static void CGContextSetLineDashWithArray(CGContextRef ctx, NSArray *dash)
{
	if (dash.count > 1)
	{
		CGFloat *dot = (CGFloat *)malloc(dash.count * sizeof(CGFloat));
        
		for (int i=0; i<dash.count; i++)
			dot[i] = [dash[i] floatValue];
		
		CGContextSetLineDash(ctx, 0, dot, dash.count);
		free(dot);
	}
	else
	{
		CGContextSetLineDash(ctx, 0, nil, 0);
	}
}

/*===================================================================
 说明:
	填充指定颜色(可以渐变)的当前路径
 ==================================================================*/
static void CGContextFillPathWithColor(CGContextRef ctx, id color)
{
	if (!color) return;
	
	if ([color isKindOfClass:[UIColor class]])
	{
		CGContextSetFillColorWithColor(ctx, [color CGColor]);
		CGContextFillPath(ctx);
	}
	else if (color)		//填充渐变色
	{
		CGContextSaveGState(ctx);
		CGContextClip(ctx);
        
        CGRect rc = CGContextGetClipBoundingBox(ctx);
		CGPoint endPoint = CGPointMake(0, CGRectGetMaxY(rc));
		
        [UIView drawLinearGradient:ctx colors:color startPoint:CGPointZero endPoint:endPoint];
		
		CGContextRestoreGState(ctx);
	}
}

/*===================================================================
 说明:
	描绘指定颜色(可以渐变)的当前路径
 ==================================================================*/
static void CGContextStrokePathWithColor(CGContextRef ctx, id color)
{
	if (!color) return;
		
	if ([color isKindOfClass:[UIColor class]])
	{
		CGContextSetStrokeColorWithColor(ctx, [color CGColor]);
		CGContextStrokePath(ctx);
	}
	else if (color)		//渐变描绘
	{
		CGContextSaveGState(ctx);
		CGContextReplacePathWithStrokedPath(ctx);
		CGContextFillPathWithColor(ctx, color);
		CGContextRestoreGState(ctx);
	}
}

/*===================================================================
 说明:
	转换为单像素的位置
 ==================================================================*/
static CGFloat pixelForValue(CGFloat v, CGFloat lineWidth)
{
	CGFloat z = [UIScreen mainScreen].scale;
	
	CGFloat pixelAdjustOffset = 0;
	if (((int)(lineWidth * z) + 1) % 2 == 0) pixelAdjustOffset = SINGLE_LINE_ADJUST_OFFSET;
	
	return lrint(v * z) / z - pixelAdjustOffset;
}

/*===================================================================
 说明:
    绘制背景
 ==================================================================*/
- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(ctx, rect.origin.x, rect.origin.y);	//解决内容移动后画布偏移,保证背景在原点位置
    
	rect.size.height -= _footerHeight;
	
	//固定脚注名称
	if (_footer.name && _footerColor)
	{
		CGSize size = [_footer.name sizeWithAttributes:@{NSFontAttributeName:_footer.textFont}];
		CGPoint point = CGPointMake(0, rect.size.height + (_footerHeight - size.height) / 2);
		
		if (_footerAlign.x == MRTextAlignmentRight)			point.x = rect.size.width - size.width;
		else if (_footerAlign.x == MRTextAlignmentCenter)	point.x = (rect.size.width - size.width) / 2;
		else if (_footerAlign.x != MRTextAlignmentLeft)		point.x = rect.size.width * _footerAlign.x - size.width / 2;
		
		if (_footerAlign.y == MRTextAlignmentTop)			point.y = rect.size.height + 2;
		else if (_footerAlign.y == MRTextAlignmentBottom)	point.y = rect.size.height + _footerHeight - size.height - 2;
		else if (_footerAlign.y != MRTextAlignmentVCenter)	point.y = rect.size.height + (_footerHeight - size.height) * _footerAlign.y;
		
		[_footer.name drawAtPoint:point withAttributes:@{NSFontAttributeName:_footer.textFont, NSForegroundColorAttributeName:_footerColor}];
	}
    
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -rect.size.height);
    
    //网格
	if (_gridBkColor)
    {
        CGContextAddRect(ctx, (CGRect){CGPointZero, rect.size});
        CGContextFillPathWithColor(ctx, _gridBkColor);
    }
	
	CGContextBeginPath(ctx);
    CGContextSetShouldAntialias(ctx, NO);
	CGContextSetLineWidth(ctx, _gridWidth);
    CGContextSetLineDashWithArray(ctx, _gridDash);
    
	//水平线
	for (int y=(_border.bottom ? 1 : 0); y<_gridSize.height + (_border.top ? 0 : 1); y++)
	{
		CGFloat y1 = pixelForValue((rect.size.height - SINGLE_LINE_WIDTH) * y / _gridSize.height, _gridWidth) + SINGLE_LINE_WIDTH;
		
		CGContextMoveToPoint(ctx, SINGLE_LINE_WIDTH, y1);
		CGContextAddLineToPoint(ctx, rect.size.width, y1);
	}
	//垂直线
	for (int x=(_border.left ? 1 : 0); x<_gridSize.width + (_border.right ? 0 : 1); x++)
	{
		CGFloat x1 = pixelForValue((rect.size.width - SINGLE_LINE_WIDTH) * x / _gridSize.width, _gridWidth) + SINGLE_LINE_WIDTH;
		
		CGContextMoveToPoint(ctx, x1, rect.origin.y);
		CGContextAddLineToPoint(ctx, x1, rect.origin.y + rect.size.height);
	}
	CGContextStrokePathWithColor(ctx, _gridColor);
	
	//外边框
    CGContextBeginPath(ctx);
	CGContextSetLineDashWithArray(ctx, nil);
	if (_border.top)
	{
        CGContextAddRect(ctx, CGRectMake(0, rect.size.height - _border.top, rect.size.width, _border.top));
	}
	if (_border.left)
	{
		CGContextAddRect(ctx, CGRectMake(0, 0, _border.left, rect.size.height));
	}
	if (_border.bottom)
	{
		CGContextAddRect(ctx, CGRectMake(0, 0, rect.size.width, _border.bottom));
	}
	if (_border.right)
	{
		CGContextAddRect(ctx, CGRectMake(rect.size.width - _border.right, 0, _border.right, rect.size.height));
	}
    CGContextFillPathWithColor(ctx, _borderColor);
	
	//Y轴刻度与参考线
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -rect.size.height);
	CGContextClipToRect(ctx, UIEdgeInsetsInsetRect(rect, _border));
	CGContextSetShouldAntialias(ctx, YES);
    
	for (MRChart *chart in _charts)
	{
		//刻度
		if (chart.textColor && chart.maxValue > chart.minValue)
		{
			for (NSInteger i=0; i<_gridSize.height; i++)
			{
				NSString *text = [NSString stringWithFormat:@"%.0f", i * (chart.maxValue - chart.minValue) / _gridSize.height + chart.minValue];
				CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:chart.textFont}];
				
				CGPoint point = CGPointMake(1, (_gridSize.height - i) * rect.size.height / _gridSize.height - size.height / 2);
				
				if (chart.textAlign.x == MRTextAlignmentRight)			point.x = rect.size.width - size.width - 1;
				else if (chart.textAlign.x == MRTextAlignmentCenter)	point.x = (rect.size.width - size.width) / 2;
				else if (chart.textAlign.x != MRTextAlignmentLeft)		point.x = rect.size.width * chart.textAlign.x - size.width / 2;
				
				if (chart.textAlign.y == MRTextAlignmentTop)			point.y -= size.height / 2;
				else if (chart.textAlign.y == MRTextAlignmentBottom)	point.y += size.height / 2;
				else if (chart.textAlign.y != MRTextAlignmentVCenter)	point.y += rect.size.height * chart.textAlign.y;
				
				[text drawAtPoint:point withAttributes:@{NSFontAttributeName:chart.textFont, NSForegroundColorAttributeName:chart.textColor}];
			}
		}
		
		//参考线
        CGFloat	scale = rect.size.height / (chart.maxValue - chart.minValue);
		for (MRChartLine *line in chart.lines)
		{
			CGFloat y = pixelForValue(rect.size.height - (line.value - chart.minValue) * scale, line.lineWidth);
			
			//线
			CGContextSetShouldAntialias(ctx, NO);
			CGContextMoveToPoint(ctx, SINGLE_LINE_WIDTH, y);
			CGContextAddLineToPoint(ctx, rect.size.width, y);
			
			CGContextSetLineWidth(ctx, line.lineWidth);
			CGContextSetLineDashWithArray(ctx, line.lineDash);
			CGContextStrokePathWithColor(ctx, line.lineColor);
			CGContextSetShouldAntialias(ctx, YES);
			
			//文本
            if (line.text.length && line.textColor)
            {
                CGSize size = [line.text sizeWithAttributes:@{NSFontAttributeName:line.textFont}];
                CGPoint point = CGPointMake(2, y - size.height / 2);
                
                if (line.textAlign.x == MRTextAlignmentRight)			point.x = rect.size.width - size.width - 2;
                else if (line.textAlign.x == MRTextAlignmentCenter)		point.x = (rect.size.width - size.width) / 2;
                else if (line.textAlign.x != MRTextAlignmentLeft)		point.x = rect.size.width * line.textAlign.x - size.width / 2;
                
                if (line.textAlign.y == MRTextAlignmentTop)				point.y -= size.height / 2;
                else if (line.textAlign.y == MRTextAlignmentBottom)		point.y += size.height / 2;
                else if (line.textAlign.y != MRTextAlignmentVCenter)	point.y += rect.size.height * line.textAlign.y;
                
                [line.text drawAtPoint:point withAttributes:@{NSFontAttributeName:line.textFont, NSForegroundColorAttributeName:line.textColor}];
            }
		}
	}
}

/*===================================================================
 说明:
	绘制图表显示区域
 ==================================================================*/
- (void)drawRect:(CGRect)rect inContext:(CGContextRef)ctx
{
	NSMutableArray	*indexes = [NSMutableArray array];
	rect.size.height -= _border.bottom + _footerHeight;
    
    //默认宽度
	if (_pointWidth == 0) self.pointWidth = rect.size.width / _pointCount;
	if (self.contentSize.height == 0)
	{
		CGSize size = self.contentSize;
		size.height = rect.size.height;
		self.contentSize = size;
	}
	
	//绘制脚注信息
    CGContextBeginPath(ctx);
	CGContextSetLineWidth(ctx, _footer.lineWidth);
	CGContextSetLineDashWithArray(ctx, _footer.lineDash);
	
    CGFloat	lastX = 0 - self.bounds.origin.x;
    for (int i=0; i<_footer.points.count; i++)
    {
        CGFloat index = [[_footer.points[i] allKeys].firstObject floatValue];
        CGFloat x = index * _pointWidth - self.bounds.origin.x;
        
		if (x >= 0)
		{
			[indexes addObject:@(index)];
			
			//文本
			NSString *text = [_footer.points[i] allValues].firstObject;
			CGSize size    = [text sizeWithAttributes:@{NSFontAttributeName:_footer.textFont}];
			CGPoint point  = CGPointMake(x - size.width / 2, rect.size.height + (_footerHeight - size.height) / 2);	//默认居中
			
			if (_footer.textAlign.y == MRTextAlignmentTop)			point.y = rect.size.height + 2;
			else if (_footer.textAlign.y == MRTextAlignmentBottom)	point.y = rect.size.height + _footerHeight - size.height - 2;
			else if (_footer.textAlign.y != MRTextAlignmentVCenter)	point.y = rect.size.height + (_footerHeight - size.height) * _footer.textAlign.y;
			
			//重直线
			if (_footer.lineWidth && _footer.lineColor)		//如果有脚注垂直线，则默认线为区域中心
			{
				CGFloat x1 = pixelForValue(x, _footer.lineWidth);
				CGContextMoveToPoint(ctx, x1, SINGLE_LINE_WIDTH);
				CGContextAddLineToPoint(ctx, x1, rect.size.height);
                
                //脚注动态位置
                if ((x + size.width / 2) > rect.size.width)
                    point.x -= size.width / 2 + x - rect.size.width;
                else if ((x - size.width / 2) < 0)
                    point.x += size.width / 2 - x;
                
                if (x > rect.size.width) break;
			}
			else	//不需绘制垂直线时，脚注按上一点中间设为中点，用于MRChartStyleSquare
			{
				CGFloat margins = LOCPIXEL(_footer.pointSize < 1.f ? _pointWidth * _footer.pointSize : _footer.pointSize);
				
				point.x -= (x - lastX - margins) / 2;
                
                //脚注动态位置
                if (x < size.width || (rect.size.width - lastX - margins) < size.width) text = nil;
                else if (point.x < 0) point.x = 0;
                else if (point.x + size.width > rect.size.width) point.x = rect.size.width - size.width;
                
                if (lastX > rect.size.width) break;
			}
			
			//绘制文本
            if (text) [text drawAtPoint:point withAttributes:@{NSFontAttributeName:_footer.textFont, NSForegroundColorAttributeName:_footer.textColor}];
		}
        
        lastX = x;
	}
    
    CGContextSetShouldAntialias(ctx, NO);
    CGContextStrokePathWithColor(ctx, _footer.lineColor);
    CGContextSetShouldAntialias(ctx, YES);
	
	//绘制曲线
	CGContextScaleCTM(ctx, 1, -1);
	CGContextTranslateCTM(ctx, 0, -rect.size.height);
	CGContextClipToRect(ctx, UIEdgeInsetsInsetRect(rect, _border));
	
	for (MRChart *chart in _charts)
	{
		if (chart.points.count && chart.maxValue > chart.minValue)
		{
			CGContextSetLineWidth(ctx, chart.lineWidth);
			CGContextSetLineDashWithArray(ctx, chart.lineDash);
			
			if (chart.style == MRChartStyleLine)
				[self drawLineChart:chart rect:rect indexes:indexes];
			else
				[self drawSquareChart:chart rect:rect];
		}
	}
}

/*===================================================================
 说明:
	绘制线式图表
 参数:
	indexes		- 标注点索引数组(为当前需要显示脚注索引)
 ==================================================================*/
- (void)drawLineChart:(MRChart *)chart rect:(CGRect)rect indexes:(NSArray *)indexes
{
	CGPoint startPoint = CGPointZero;
	CGPoint endPoint   = CGPointZero;
	CGPoint lastPoint  = CGPointZero;
	
	BOOL	bStart	   = NO;
	CGFloat	scale      = rect.size.height / (chart.maxValue - chart.minValue);
	
	NSMutableArray	*points = [NSMutableArray array];
	
	//生成路径
	NSInteger idx = 0;
	CGMutablePathRef path = CGPathCreateMutable();
	
	for (int i=0; i<chart.points.count; i++)
	{
		CGFloat index, value;
		
		if (chart.points[i][@"index"])
		{
			index = [chart.points[i][@"index"] floatValue];
			value = [chart.points[i][chart.name] floatValue];
		}
		else
		{
			index = [[chart.points[i] allKeys].firstObject floatValue];
			value = [[chart.points[i] allValues].firstObject floatValue];
		}
		
		CGFloat x = index * _pointWidth - self.bounds.origin.x;
		endPoint = CGPointMake(x, (value - chart.minValue) * scale);
		
		//起始点检测
		if ((x < 0 || i == 0) && !bStart)
		{
			startPoint = endPoint;
		}
		if (x >= 0 && !bStart)
		{
			bStart = YES;
			lastPoint = startPoint;
            
			CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
		}
		//结束点检测
		if (bStart && i)
		{
			if (chart.pointSize == 0)		//不需要绘制数据点时，使用二次曲线平滑绘制
			{
				CGPoint pt = CGPointMake((lastPoint.x + endPoint.x) / 2, (lastPoint.y + endPoint.y) / 2);
				CGPathAddQuadCurveToPoint(path, NULL, lastPoint.x, lastPoint.y, pt.x, pt.y);
			}
			else
				CGPathAddLineToPoint(path, NULL, endPoint.x, endPoint.y);
			
			lastPoint = endPoint;
			if (x > rect.size.width) break;
		}
		
		//脚注对应数据点
		for (; idx<indexes.count; idx++)
		{
			CGFloat idxs = [indexes[idx] floatValue];
			
			if (index < idxs)
				break;
			else if (index == idxs)
				[points addObject:[NSValue valueWithCGPoint:endPoint]];
		}
	}
	
	CGPathAddLineToPoint(path, NULL, endPoint.x, endPoint.y);
	
	//描边与填充
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGContextSetLineCap(ctx, kCGLineCapRound);
	CGContextSetLineJoin(ctx, kCGLineJoinRound);
	
	if (!CGPathIsEmpty(path))
	{
		if (chart.fillColor)
		{
			CGFloat h = (0 - chart.minValue) * scale;
			CGMutablePathRef fill = CGPathCreateMutableCopy(path);
			
			CGPathAddLineToPoint(fill, NULL, endPoint.x, h);
			CGPathAddLineToPoint(fill, NULL, startPoint.x, h);
			CGPathCloseSubpath(fill);
			
			CGContextAddPath(ctx, fill);
			CGContextFillPathWithColor(ctx, chart.fillColor);
			CGPathRelease(fill);
		}
		
		if (chart.lineColor)
		{
			CGContextAddPath(ctx, path);
			CGContextStrokePathWithColor(ctx, chart.lineColor);
		}
	}
    
    CGPathRelease(path);
	
	//数据点
	CGContextSetLineDashWithArray(ctx, nil);
	if (points.count && chart.pointSize)
	{
		CGFloat r = chart.pointSize * 2;
		CGRect rect = CGRectMake(0, 0, r * 2, r * 2);
		
		for (NSValue *value in points)
		{
			CGPoint point = [value CGPointValue];
			rect.origin = CGPointMake(point.x - r, point.y - r);
			
			//底圆
			CGContextAddPath(ctx, [UIBezierPath bezierPathWithOvalInRect:rect].CGPath);
			CGContextFillPathWithColor(ctx, rgba(255, 255, 255, .8));
			
			//中心圆
			CGContextAddPath(ctx, [UIBezierPath bezierPathWithOvalInRect:CGRectInset(rect, chart.pointSize, chart.pointSize)].CGPath);
			CGContextStrokePathWithColor(ctx, chart.lineColor);
		}
	}
}

/*===================================================================
 说明:
	绘制柱状图表
 ==================================================================*/
- (void)drawSquareChart:(MRChart *)chart rect:(CGRect)rect
{
	//计算最大最小
	NSUInteger	_minRow = 0, _maxRow = 0;
	CGFloat _minSpeed = 0, _maxSpeed = 0;
	
	for (NSUInteger i=0; i<chart.points.count; i++)
	{
		CGFloat value;
		if (chart.points[i][@"index"])
			value = [chart.points[i][chart.name] floatValue];
		else
			value = [[chart.points[i] allValues].firstObject floatValue];
		
		if (value > _maxSpeed || i == 0) {_maxRow = i; _maxSpeed = value;}
		if (value < _minSpeed || i == 0) {_minRow = i; _minSpeed = value;}
	}
	
	//绘制柱状
	CGContextRef ctx = UIGraphicsGetCurrentContext();
    
	CGContextSetLineCap(ctx, kCGLineCapButt);
	CGContextSetLineJoin(ctx, kCGLineJoinMiter);
	
	CGFloat	scale = rect.size.height / (chart.maxValue - chart.minValue);
	CGFloat	lastX = 0 - self.bounds.origin.x;
	
	CGFloat margins = LOCPIXEL(chart.pointSize < 1.f ? _pointWidth * chart.pointSize : chart.pointSize);
	
	for (int i=0; i<chart.points.count; i++)
	{
		CGFloat index, value;
		
		if (chart.points[i][@"index"])
		{
			index = [chart.points[i][@"index"] floatValue];
			value = [chart.points[i][chart.name] floatValue];
		}
		else
		{
			index = [[chart.points[i] allKeys].firstObject floatValue];
			value = [[chart.points[i] allValues].firstObject floatValue];
		}
		
		CGFloat x = index * _pointWidth - self.bounds.origin.x;
		CGPoint point = CGPointMake(x, (value - chart.minValue) * scale);
        
		//起始点检测
		if (x >= 0)
		{
            //上边线
            CGMutablePathRef path = CGPathCreateMutable();
            CGPathMoveToPoint(path, NULL, point.x, point.y);
            CGPathAddLineToPoint(path, NULL, lastX + margins, point.y);
            CGContextAddPath(ctx, path);
            
			id color = chart.lineColor;
			if (_minRow != _maxRow)
			{
				if (i == _minRow && chart.minLineColor) color = chart.minLineColor;
				if (i == _maxRow && chart.maxLineColor) color = chart.maxLineColor;
			}
			CGContextStrokePathWithColor(ctx, color);
			
            //填充区域
            CGMutablePathRef fill = CGPathCreateMutableCopy(path);
            CGPathAddLineToPoint(fill, NULL, lastX + margins, 0);
            CGPathAddLineToPoint(fill, NULL, point.x, 0);
            CGPathCloseSubpath(fill);
			CGContextAddPath(ctx, fill);
			
			color = chart.fillColor;
			if (_minRow != _maxRow)
			{
				if (i == _minRow && chart.minFillColor) color = chart.minFillColor;
				if (i == _maxRow && chart.maxFillColor) color = chart.maxFillColor;
			}
			CGContextFillPathWithColor(ctx, color);
            
            CGPathRelease(fill);
            CGPathRelease(path);
			
			if (x > rect.size.width) break;
		}
		
		lastX = point.x;
	}
}

#pragma mark - 图表与数据
/*===================================================================
 说明:
    添加图表
 ==================================================================*/
- (MRChart *)addChartWithName:(NSString *)name
{
    MRChart *chart = [[MRChart alloc] initWithChartView:self];
    chart.name = name;
    
    [_charts addObject:chart];
    return chart;
}

- (MRChart *)chartWithName:(NSString *)name
{
	for (MRChart *chart in _charts)
	{
		if ([chart.name isEqualToString:name]) return chart;
	}
	return nil;
}

/*===================================================================
 说明:
	移除图表
 ==================================================================*/
- (void)removeChart:(MRChart *)chart
{
	if ([_charts containsObject:chart])
		[_charts removeObject:chart];
}

- (void)removeChartWithName:(NSString *)name
{
	[self removeChart:[self chartWithName:name]];
}

/*===================================================================
 说明:
	添加数据点
 ==================================================================*/
- (void)addPointWithArray:(NSArray *)points
{
	for (NSDictionary *dict in points)
		[self addPointWithDictionary:dict];
}

- (void)addPointWithDictionary:(NSDictionary *)dictionary
{
	NSInteger index = [dictionary.allKeys.firstObject intValue];
	NSDictionary *dict = dictionary.allValues.firstObject;
	
	for (MRChart *chart in _charts)
	{
		id obj = dict[chart.name];
		if (obj) [chart addPointWithDictionary:@{@(index):obj}];
	}
}

@end

@implementation MRChartContentView
- (void)drawRect:(CGRect)rect
{
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	MRChartView *view = (MRChartView *)self.superview;
	
	[view drawRect:rect inContext:ctx];
}
@end
